<!--密码修改-->
<template>
    <a-modal
            v-model="visible"
            :width="550"
            title="修改密码"
            :maskClosable="false"
            :destroyOnClose="true"
            @ok="saveEditPass"
            @cancel="cancel"
            okText="确定"
            cancelText="取消"
    >
        <a-form :form="form" @keydown.native.enter.prevent="saveEditPass">
            <a-input type="password" style="position: fixed; bottom: -99999px"></a-input>
            <a-form-item v-for="(k, index) in formPwd" :key="index" v-bind="formStyle" :label="k.label">
                <a-input
                        v-model="k.value"
                        :type="k.pwdType"
                        style="position: relative;"
                        :id="'refocus' + index"
                        @change="valideNewPassword(k.index, k.value, k.label)"
                        onpaste="return false"
                        oncopy="return false"
                        oncut="return false"
                >
                    <a-icon slot="suffix" :type="k.eyeStatusName" @click="showOldPass(k)" style="  color: rgba(0,0,0,.65)" />
                </a-input>
                <div style="color:red; position: absolute; left: 0; top: 18px; font-size: 11px">{{ k.errMsg }}</div>
            </a-form-item>
            <div style="padding: 0 15px 0 40px">
                <span style="color: red">验证规则:</span>
                <br />
                <span style="color: red">1、密码不能为空</span>
                <br />
                <span style="color: red">2、密码应满足长度8-16字符，且必须包含大写字母，小写字母和数字</span>
                <br />
                <span
                        style="
                color: red"
                >
                    3、密码可输入_/@#$*.&lt;&gt;特殊字符
                </span>
            </div>
        </a-form>
    </a-modal>
</template>
<script>
    // const Base64 = require('js-base64').Base64;
    const shajs = require('sha.js');
    export default {
        name: 'editPassword',
        data () {
            const valideRePassword = (rule, value, callback) => {
                if (value !== this.form.newPass) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            };
            const res1 = /^[a-zA-Z0-9.]+$/;
            const res2=/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/;
            const valideNewPassword = (rule, value, callback) => {
                if (!value || value.trim().length === 0) {
                    callback(new Error('必填项'));
                } else if(value.length > 16 || value.length < 6){
                    callback(new Error('请输入6-16位有效密码！'));
                } else if (!res1.test(value)) {
                    callback(new Error('密码必须包含大写字母，小写字母和数字中两种及以上！'));
                } else if (!res2.test(value)) {
                    callback(new Error('密码必须包含大写字母，小写字母和数字中两种及以上！'));
                } else if (value === this.form.oldPass) {
                    callback(new Error('新旧密码不可一致！'));
                }  else {
                    callback();
                }
            };
            const validePassword = (rule, value, callback) => {
                if (!value || value.trim().length === 0) {
                    callback(new Error('必填项'));
                } else {
                    callback();
                }
            };
            return {
                visible: false,
                form: this.$form.createForm(this),
                formStyle: {
                    labelCol: { span: 6 },
                    wrapperCol: { span: 17 }
                },
                formPwd: [
                    { index: 0, label: '原密码', name: 'oldPassword', value: '', errMsg: '', pwdType: 'password', eyeStatusName: 'eye-invisible' },
                    { index: 1, label: '新密码', name: 'newPassword', value: '', errMsg: '', pwdType: 'password', eyeStatusName: 'eye-invisible' },
                    { index: 2, label: '确认新密码', name: 'rePassword', value: '', errMsg: '', pwdType: 'password', eyeStatusName: 'eye-invisible' }
                ],
                isActive: false,
                isCurKey: true,
                firstChart: false,
                defaultPsw: sessionStorage.getItem ('defaultPsw'),
            };
        },
        methods: {
            showModal() {
                this.visible = true
                setTimeout(function() {
                    document.getElementById('refocus0').focus()
                }, 200)
            },
            /**
             * Function    : valideNewPassword
             * Description : 验证新密码的规则一致
             * Input       : none
             * Return      : none
             */
            valideNewPassword(index, value, label) {
                let msg = ''
                if (typeof value === 'undefined') {
                    return
                }
                value = value.replace(/\s/g, '')
                const res1 = /^[0-9A-Za-z_/@#$*.<>]+$/
                const res2 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/
                if (value.length > 16) {
                    value = value.substring(0, 16)
                }
                this.formPwd[index].value = value
                if (index !== 2) {
                    if (value.trim().length === 0) {
                        msg = '请输入包含大小写字母、数字或_/@#$*.<>有效密码'
                    } else if (!res1.test(value)) {
                        msg = '请输入包含大小写字母、数字或_/@#$*.<>有效密码'
                    } else if (value.length > 16 || value.length < 8) {
                        msg = '请输入8-16位有效密码'
                    } else {
                        if (!res2.test(value)) {
                            msg = '请输入包含大小写字母、数字或_/@#$*.<>有效密码'
                        } else if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value === this.formPwd[2].value) {
                            this.formPwd[2].errMsg = ''
                            if (this.formPwd[1].value === 'QaSky20191818' && index === 1) {
                                msg = '禁止输入初始化密码'
                            }
                        } else if (this.formPwd[1].value === 'QaSky20191818' && index === 1) {
                            msg = '禁止输入初始化密码'
                        } else if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value !== this.formPwd[2].value) {
                            this.formPwd[2].errMsg = '两次输入密码不一致'
                        }
                    }
                    this.formPwd[index].errMsg = msg
                } else {
                    if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value !== this.formPwd[2].value) {
                        this.formPwd[2].errMsg = '两次输入密码不一致'
                    } else if (this.formPwd[1].value && this.formPwd[2].value && this.formPwd[1].value === this.formPwd[2].value) {
                        this.formPwd[2].errMsg = ''
                    }
                }
            },
            // 是否明码展示所填密码
            showOldPass(k) {
                if (k.pwdType === 'password') {
                    k.pwdType = 'text'
                    k.eyeStatusName = 'eye'
                } else {
                    k.pwdType = 'password'
                    k.eyeStatusName = 'eye-invisible'
                }
            },
            /**
             * Function    : saveEditPass
             * Description : 表单提交
             * Input       : data
             * Return      : none
             */
            saveEditPass() {
                let isNull = false
                let isRight = true
                this.formPwd.forEach(item => {
                    if (item.value === '' || item.value === undefined) {
                        isNull = true
                        item.errMsg = item.label + '不能为空'
                    }
                    if (item.errMsg !== '') {
                        isRight = false
                    }
                })
                this.form.validateFields((err, value) => {
                    if (isNull || !isRight) {
                        return
                    }
                    if (!err) {
                        let param = {
                            'originPassword': shajs('sha256').update(this.formPwd[0].value).digest('base64'),//Base64.encode(this.sureForm.oldPass),
                            'password': shajs('sha256').update(this.formPwd[1].value).digest('base64'),//Base64.encode(this.sureForm.newPass),
                            'userName': sessionStorage.getItem('user')
                        };
                        let _this = this
                        this.$store.dispatch('updPasswordAct', param).then(response => {
                            if (response.code === 0) {
                                _this.visible = false
                                _this.formPwd.forEach(item => {
                                    item.value = ''
                                    item.errMsg = ''
                                    item.pwdType = 'password'
                                    item.eyeStatusName = 'eye-invisible'
                                })
                                _this.$message.success('修改成功，请重新登录')
                                sessionStorage.clear()
                                sessionStorage.setItem('interceptorMsg', '修改成功，请重新登录')
                                _this.$router.push({
                                    name: 'login'
                                })
                            } else {
                                _this.$message.error (response.message)
                                if(response.code === 409){
                                    this.visible = false;
                                    sessionStorage.clear();
                                    sessionStorage.setItem('interceptorMsg', '超过可重试次数，用户已经被锁定')
                                    this.$router.push({
                                        name: 'login'
                                    });
                                }
                            }
                        });
                    }
                })
            },
            cancel() {
                this.visible = false
                let _this = this
                setTimeout(function() {
                    _this.formPwd.forEach(item => {
                        item.value = ''
                        item.errMsg = ''
                        item.pwdType = 'password'
                        item.eyeStatusName = 'eye-invisible'
                    })
                }, 100)
                if( _this.defaultPsw === '1' ){
                    sessionStorage.clear();   // 未修改密码直接取消应该退出至登录页面
                    this.$router.push({
                        name: 'login'
                    });
                }
            }
        }
    };
</script>
